package jh.com.jhappbf.dispatchcar;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;

/**
 * author : wwh
 * e-mail : 953889276@qq.com
 * time   : 2018/9/4 16:25
 * desc   :
 *
 * @author Administrator
 */
public class UploadReceipt extends AbActivity implements OnClickListener {

    private static final int TAKEPHOTO = 0x0001;
    private Button mCamera, mUpload;
    private EditText mRealNet;
    private ImageView mPicture;
    private TextView mSaverId; //  saverId
    private String mPhotoName;
    private String mPhotoInfo = "";
    private String id;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.activity_upload_receipt);

        AbTitleBar mAbTitleBar = getTitleBar();
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleText("衡安移动管理");
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        initView();
    }

    private void initView() {
        mCamera = findViewById(R.id.receipt_camera);
        mUpload = findViewById(R.id.receipt_upload);
        mRealNet = findViewById(R.id.receipt_real_net);
        mPicture = findViewById(R.id.receipt_picture);
        mSaverId = findViewById(R.id.receipt_saverid);
        mCamera.setOnClickListener(this);
        mUpload.setOnClickListener(this);
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        mSaverId.setText("磅单号:" + id);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.receipt_camera:
                takePhoto();
                break;
            case R.id.receipt_upload:
                uploadReceipt();
                break;
            default:

        }
    }

    private void uploadReceipt() {

        String methodName = "uploadReceipt";
        ArrayList<String> params = new ArrayList<>();
        ArrayList<String> values = new ArrayList<>();

        params.add("id");
        params.add("photo");
        params.add("realNet");
        params.add("operate");


        if (id.trim().length() > 0) {
            values.add(id);
        } else {
            Toast.makeText(this, "磅单id不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mPhotoInfo.length() > 0) {
            values.add(mPhotoInfo);
        } else {
            Toast.makeText(this, "请拍摄磅单照片", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mRealNet.getText().toString().trim().length() > 0) {
            values.add(mRealNet.getText().toString());
        } else {
            Toast.makeText(this, "请填写实收净重", Toast.LENGTH_SHORT).show();
            return;
        }
        values.add(State.mName);

        values.add(id);
        Listener<String> listener = response -> {
            JSONObject object = JsonHelper.getJsonObject(response);
            if (object != null) {
                String result = object.optString("result");
                String memo = object.optString("memo");
                if ("true".equals(result)) {
                    Toast.makeText(UploadReceipt.this, "磅单上传成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(UploadReceipt.this, memo, Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(UploadReceipt.this, "上传失败", Toast.LENGTH_SHORT).show();
            }
        };
        ErrorListener errorListener = volleyError -> Toast.makeText(UploadReceipt.this, "网络异常！", Toast.LENGTH_SHORT).show();

        VolleyCallWebService webService = new VolleyCallWebService(methodName, params, values, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(this).addRequest(webService);

    }

    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mPhotoName = System.currentTimeMillis() + ".jpg";

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //指定调用相机拍照后的照片存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                    Environment.getExternalStorageDirectory() + "/jinheng", mPhotoName)));
            startActivityForResult(intent, TAKEPHOTO);

        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                    this.getFilesDir().getAbsolutePath() + "/jinheng", mPhotoName)));
            startActivityForResult(intent, TAKEPHOTO);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKEPHOTO && resultCode == RESULT_OK) {

            Bitmap bitmap = BitmapFactory.decodeFile(Environment.
                    getExternalStorageDirectory().getPath() + "/jinheng/" + mPhotoName);

            Bitmap upBitmap = zoomImage(bitmap, bitmap.getWidth() / 4, bitmap.getHeight() / 4);
            mPicture.setImageBitmap(upBitmap);
            mPhotoInfo = bitmapToString(upBitmap);
        }
    }

    public static Bitmap zoomImage(Bitmap bigImage, double newWidth, double newHeight) {
        // 获取这个图片的宽和高
        float width = bigImage.getWidth();
        float height = bigImage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bigImage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    //把bitmap转换成字符串
    public static String bitmapToString(Bitmap bitmap) {
        String string;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
        byte[] bytes = baos.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }
}
